import React from 'react'
import { connect } from 'dva'
import { Form ,Modal,message,Upload,Button,Select,Radio,Input } from 'antd'
import { Link, hashHistory } from 'dva/router'
import config from 'config/config'
import $ from 'jquery'
import FlagBtn from 'widget/FlagBtn/FlagView'
import { mapStateToProps } from 'utils/view_utils'
import styles from './customerListStyle.less'
import ListPage from 'widget/PageTmpl/ListPage'
import classnames from 'classnames/bind';
let cx=classnames.bind(styles);
const { Option } = Select;

const radioStyle = {
  display: 'block',
  height: '30px',
  lineHeight: '30px',
};

const customerListView = function({dispatch, model, form}) {
  // 表单的子函数
  const {resetFields, getFieldDecorator, validateFields, setFieldsValue} = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  // modelObj.xxx获取model中状态机的值
  let {endflag,methodList,detail,areaList,products,teamList,seleTeamList,userList,dialogModal,biz,id,selectedRows} = modelObj
  let pageProps = {
    // ---------- 界面部分 ----------
    ui: {
      // 页面接口地址
      // api_url: `admin/commissionApply/list`,
      api_url: `zituo-admin/a/client/xftClientBuildingRelation`,
      // 接口方式
      method: "POST",
      // "data_field_name":"data",
      app: "",
      // 接口参数
      params: {
        pageSize:'10',
        pageNo:'1',
        // areaName: '4xEAAAAADJzM567U-0000',
        // cityName: '4xEAAAFnrAjM567U',
        // projectName: 'H102018022',
        // channel: 'SD00104'
        },
      // 模拟数据 - 用于开发需要，若填充了上面的api_url之后，请将此项设置为null
      // "mockData": mockData,
      mockData: null,
      // 查询栏
      search_bar: {
        fields: [
          {
            en_name: 'areaId',
            zh_name: '区域',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: areaList,
          },
          {
            en_name: 'projectId',
            zh_name: '项目',
            elem_type: 'SelectFilter',
            elem_valid_type: 'string',
            showSearch: true,
            cmpt_items: products,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.areaId){ 
                dispatch({
                  type: `${namespace}/filterProjectList`,
                  payload: {}
                })
              }
            },
          },
          {
            en_name: 'clientName',
            zh_name: '客户姓名',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'teamName',
            zh_name: '团队',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: teamList,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.projectId){ 
                getTeams(biz.queryForm.projectId)
              }
            },
          },
          {
            en_name: 'brokerName',
            zh_name: '报备人',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'methodId',
            zh_name: '拓客方式',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: methodList,
            onFocus:()=>{
              if(biz.queryForm && biz.queryForm.areaId){ 
                dispatch({
                  type: `${namespace}/getmMethod`,
                  payload: {}
                })
              }
            },
          },
          {
            en_name: 'clientStatusName',
            zh_name: '客户状态',
            elem_type: 'Select',
            elem_valid_type: 'string',
            cmpt_items: [
              {
                  value: '重要客户',
                  label: '重要客户'
               }, 
              {
                  value: '待报备',
                  label: '待报备'
              },
              {
                  value: '已报备',
                  label: '已报备'
              },
              {
                  value: '已到访',
                  label: '已到访'
              }, 
              {
                  value: '已认筹',
                  label: '已认筹'
              },
              {
                  value: '已认购',
                  label: '已认购'
              },
              {
                  value: '已签约',
                  label: '已签约'
              },
              {
                  value: '已款清',
                  label: '已款清'
              },
              {
                  value: '已流失',
                  label: '已流失'
              },
              {
                  value: '将流失',
                  label: '将流失'
              },
              {
                  value: '无效待报备',
                  label: '无效待报备'
              }
          ],
          },
          {
            en_name: 'phone',
            zh_name: '客户手机号',
            elem_type: 'Input',
            elem_valid_type: 'string',
          },
          {
            en_name: 'reportTime',
            zh_name: '报备时间',
            elem_type: 'Date',
            format: 'YYYY-MM-DD',
            // query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            // double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['reportStartTime', 'reportEndTime'],
            elem_valid_type: 'string'
          },
          {
            en_name: 'visitedConfirmTime',
            zh_name: '到访时间',
            elem_type: 'Date',
            format: 'YYYY-MM-DD',
            // query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            // double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['arriveStartTime', 'arriveEndTime'],
            elem_valid_type: 'string'
          },
          {
            en_name: 'orderTime',
            zh_name: '认购时间',
            elem_type: 'Date',
            format: 'YYYY-MM-DD',
            // query_format: "YYYY-MM-DD HH:mm:ss",   // 请求参数, 当请求参数和显示时格式不同可通过该参数区分
            // double: true,  // 日期范围组件 使用"YYYY-MM-DD HH:mm:ss"格式时, 显示不全时可使用该参数, 将占据两格位置
            split_keys: ['orderStartTime', 'orderEndTime'],
            elem_valid_type: 'string'
          }
        ],
        searchHandler: (e) => { // 自定义搜索按钮回调函数，点击搜索时触发
          console.log('search click')
        },
        resetHandler: () => { // 自定义重置按钮回调函数，点击重置时触发
          console.log('reset click')
        },
        searchCallback: params => { // 自定义搜索完成后的后调函数, 搜索完成后触发, 并将本次搜索的参数传入
          console.log('search finish', params)
        },
        pasteTargetList: [  // 列表组件中将输入框的en_name作为默认id(也可以通过id另外设置)
          'channel',  // 将需要粘贴事件拦截的输入框id以数组的形式传入, 该参数对应PasteFromClipboard组件的targetList参数
        ]
      },
      // 数据表格  序号 是否生效 项目名称  佣金方案名称 方案生效日期 方案失效日期 审批人 审批通过日期   提交人 提交日期  创建人 创建日期
      table:
        {
          rowSelectionInfo: {
            type: 'checkbox',
          },
          status_params: "status=0",
          status_text: "全部",
          // 表头字段列表
          scroll: { x: 2200},
          fields: [
            {
              en_name: "ruleNo",
              zh_name: "编号",
              width: 60,
              render: (a, item, index, d, e, f) => {
                return index+1
              },
            },
            {
              en_name: "areaName",
              zh_name: "区域",
            },
            {
              en_name: "projectName",
              zh_name: "项目",
            },
            {
              en_name: "channel",
              zh_name: "渠道",
            },
            {
              en_name: "teamName",
              zh_name: "团队",
            },
            {
                en_name: "brokerName",
                zh_name: "报备人",
            },
            {
                en_name: "creater",
                zh_name: "提交人",
            },
            {
              en_name: "clientName",
              zh_name: "客户姓名",
            },
            {
              en_name: "clientPhones",
              zh_name: "客户手机号码",
            },
            {
                en_name: "clientStatusName",
                zh_name: "状态",
            },
            {
                en_name: "zituoMethodName",
                zh_name: "拓客方式",
            },
            {
              en_name: "gender",
              zh_name: "性别",
            },
            {
                en_name: "intentionLevel",
                zh_name: "意向等级",
            },
            {
              en_name: "reportTime",
              zh_name: "报备时间",
              render:(a, item, index, d, e, f)=>{
                return item.reportTime
              }
            },
            {
              en_name: "visitedConfirmTime",
              zh_name: "到访时间",
              render:(a, item, index, d, e, f)=>{
                return item.visitedConfirmTime
              }
            },
            {
              en_name: "orderTime",
              zh_name: "认购时间",
              render:(a, item, index, d, e, f)=>{
                return item.orderTime
              }
            },
            {
              en_name: "edit",
              zh_name: "操作",
              width:80,
              fixed:'right',
              render: (a, item, index, d, e, f) => {
                return (
                  <span>
                      <FlagBtn node={<a onClick={() => checkOrEditSkip('check',item)}>查看</a>} btnId={''}> </FlagBtn>
                  </span>
                )
              },
            }
          ],
        },
      // 操作栏
      action_bar: [
        {
          label: "导出",
          type: "primary",
          rowSelection:[],
          onClick: (e,row) =>{
            // if(row.length<=0){
            //   message.warn('请选择一项导出数据')
            //   return
            // }
            // id = row[0].id
            down()
          }
        },
        {
          label: "客户转移",
          type: "primary",
          rowSelection:[],
          onClick: (e,row) =>{
            if(row.length<=0){
              message.warn('请选择一项转移数据')
              return
            }
            id = row[0].projectId
            selectedRows = row
            dispatch({
              type: `${namespace}/updateStore`,
              payload: { selectedRows }
            })
            getTeams(id,'select')
            updateCancel()
          }
        }
      ]
    },
  }
  
  //查看，编辑
  function checkOrEditSkip(type,item){
      hashHistory.push({
        pathname: '/home/expandManage/customerInfo',
        query: {actionType: type, id:item.uniqueId ,status: item.clientStatusName}
      })
  }

  function updateCancel(){
    userList = []
    dialogModal.visible = !dialogModal.visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { dialogModal,userList }
    })
  }
  // 获取团队
  function getTeams(id,type){
    dispatch({
      type: `${namespace}/getTeamsByProjectId`,
      payload: {id:id,type:type}
    })
  }
  // 转移确认
  function onSubmit(){
    if(!detail.receiverId){
      message.warning('请选择人员再确认')
      return
    }
    dispatch({
      type: `${namespace}/submit`,
      payload: {}
    })
  }

  function down(){
    dispatch({
      type: `${namespace}/down`,
      payload: {}
    })
  }

  //表单改变时
  function inputChange (value, name) {
    let obj = {[name]: value}
    detail = Object.assign(detail, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detail}
    })
  }
   //团队改变时
  function teamChange (value, name) {
    let obj = {[name]: value}
    detail = Object.assign(detail, obj)
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {detail}
    })
    dispatch({
      type: `${namespace}/getTeamUser`,
      payload: {teamId: value}
    })
  }

  if (!!modelObj.biz) {
		pageProps.biz = modelObj.biz
		pageProps.biz.syncBackCbf = (biz) => {
			dispatch({
				type: `${namespace}/updateStore`,
				payload: { biz }
			})
		}
  }

  return (
    <div className={cx('pageLayout')}>
      {endflag&& <ListPage pageProps={pageProps}/>}
     
      <Modal
          title="转移"
          visible={dialogModal.visible}
          destroyOnClose={true}
          onOk={() => { onSubmit() }}
          onCancel={() => { updateCancel() }}
        >
          <span>团队：</span>
            <Select style={{width: '70%'}} placeholder='请选择区域' onChange={(e) => { teamChange(e, 'team') }}>
                {seleTeamList.map((item)=>{
                    return <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
                  })}
            </Select>
            <div style={{padding:'0 20px'}}>
              <Radio.Group onChange={(e) => { inputChange(e.target.value, 'receiverId') }}>
                {userList.map((item)=>{
                    return <Radio style={radioStyle} key={item.userId} value={item.userId}>{item.userName}</Radio>
                  })}
              </Radio.Group>
            </div>
        </Modal>
    </div>
  )
  
}
// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(customerListView))
